#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/ipc.h>
#include <sys/types.h>
#include <sys/shm.h>
#include <string.h>
#include <unistd.h>

#define N 1024

typedef struct
{
    pid_t pid;
    char text[N];
}SHMBUF;

void handler(int signo) {printf("signo=%d\n", signo);}
int main()
{
	int shmid;
    SHMBUF *shmadd;
    key_t key;
    pid_t peerpid;

    if ((key = ftok(".", 'a')) == -1)
    {
        perror("ftok");
        exit(-1);
    }

    signal(SIGUSR1, handler);

	if ((shmid = shmget(key, sizeof(SHMBUF), 0666 | IPC_CREAT | IPC_EXCL)) == -1)
	{
        if (errno == EEXIST)
        {
            shmid = shmget(key, sizeof(SHMBUF), 0666);
	        if ((shmadd = (SHMBUF *)shmat(shmid, NULL, 0)) == (SHMBUF *)-1)
        	{
	         	perror("shmat");
		        exit(-1);
        	}
            peerpid = shmadd->pid;
            shmadd->pid = getpid();
            kill(peerpid, SIGUSR1);
        }
        else
        {
    	    perror("shmget");
	    	exit(-1);
        }
	}
    else    //first process
    {
	    if ((shmadd = (SHMBUF *)shmat(shmid, NULL, 0)) == (SHMBUF *)-1)
    	{
	    	perror("shmat");
		    exit(-1);
    	}
        shmadd->pid = getpid();
        pause();
        peerpid = shmadd->pid;
    }

    while (1)
    {
        pause();
        printf("read %s\n", shmadd->text);
        if (strncmp(shmadd->text, "quit", 4) == 0)
        {
	        if (shmdt(shmadd) == -1)
        	{
		        perror("shmdt");
        	}
            exit(0);
        }
       // sleep(1);
       usleep(100000);
       kill(peerpid, SIGUSR1);
    }
    exit(0);
}
